package com.yougou.ui.home;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.yougou.base.BaseViewModel;
import com.yougou.data.model.Floor;
import com.yougou.data.model.Swiper;
import com.yougou.data.repository.HomeRepository;

import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class HomeViewModel extends BaseViewModel {
    
    private final HomeRepository mRepository;
    private final MutableLiveData<List<Swiper>> mSwiperList = new MutableLiveData<>();
    private final MutableLiveData<List<Floor>> mFloorList = new MutableLiveData<>();
    private final MutableLiveData<Boolean> mLoading = new MutableLiveData<>(false);
    private final MutableLiveData<String> mError = new MutableLiveData<>();
    
    public HomeViewModel() {
        mRepository = new HomeRepository();
    }
    
    
    public LiveData<List<Swiper>> getSwiperList() {
        return mSwiperList;
    }
    
    
    public LiveData<List<Floor>> getFloorList() {
        return mFloorList;
    }
    
    
    public LiveData<Boolean> isLoading() {
        return mLoading;
    }
    
    
    public LiveData<String> getError() {
        return mError;
    }
    
    
    public void loadHomeData() {
        loadSwiperData();
        loadFloorData();
    }
    
    
    private void loadSwiperData() {
        mLoading.setValue(true);
        addDisposable(
            mRepository.getSwiperData()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    response -> {
                        mLoading.setValue(false);
                        if (response.isSuccess() && response.getMessage() != null) {
                            mSwiperList.setValue(response.getMessage());
                        } else {
                            mError.setValue("获取轮播图失败");
                        }
                    },
                    error -> {
                        mLoading.setValue(false);
                        mError.setValue("网络错误: " + error.getMessage());
                    }
                )
        );
    }
    
    
    private void loadFloorData() {
        addDisposable(
            mRepository.getFloorData()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    response -> {
                        if (response.isSuccess() && response.getMessage() != null) {
                            mFloorList.setValue(response.getMessage());
                        } else {
                            mError.setValue("获取楼层数据失败");
                        }
                    },
                    error -> {
                        mError.setValue("网络错误: " + error.getMessage());
                    }
                )
        );
    }
}

